import cv2 as cv
import numpy as np

filePath = '../test_datas/numberOne.png'
img = cv.imread(filePath)
imgGray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

thresh, maxValue = 127, 255
threshType = cv.THRESH_BINARY
ret, thresh = cv.threshold(imgGray, thresh, maxValue, threshType)

retrievalMode = cv.RETR_TREE
approxMethod = cv.CHAIN_APPROX_NONE
contours, hierachy = cv.findContours(thresh, retrievalMode, approxMethod)

cnt = contours[1]
x,y,w,h = cv.boundingRect(cnt)
center,size,angle = cv.minAreaRect(cnt)

imgBackGround = np.zeros(img.shape, np.uint8)
cv.drawContours(imgBackGround, contours, 1, (255,255,255), -1)

#draw straight box
cv.rectangle(imgBackGround,(x,y),(x+w, y+h),(0,255,0),2)

#draw rotated box
box = cv.boxPoints((center,size,angle))
box = np.int0(box)
cv.drawContours(imgBackGround,[box],0,(0,0,255),2)

cv.imshow("img", img)
cv.imshow("imgBG", imgBackGround)
cv.waitKey(0)
cv.destroyAllWindows()